import React, { useLayoutEffect } from 'react';
import { View, Text, ScrollView, router, hideMenuButton, publishDps, Image } from '@ray-js/ray';
import clsx from 'clsx';
import { useDevice, useProps } from '@ray-js/panel-sdk';
import { useThrottleFn } from 'ahooks';
import { getCachedSystemInfo } from '@/api/getCachedSystemInfo';
import Strings from '@/i18n';
import { useSelector } from 'react-redux';
import { ReduxState } from '@/redux';
import { Switch, NavBar, SwipeCell } from '@ray-js/smart-ui';

import styles from './index.module.less';
import { decodeClock, encodeClock, repeatArrtoStr } from '@/utils';

const HeaderHeight = 59;

const sysInfo = getCachedSystemInfo();

export function Home() {
  const deviceName = useDevice(d => d?.devInfo?.name || 'devname');

  const { clockNames } = useSelector((state: ReduxState) => state?.cloudState) || {};

  useLayoutEffect(() => {
    hideMenuButton();
  }, []);

  const timeMode = useProps(props => props.time_mode);

  const alarm1 = useProps(props => props.alarm_1);
  const alarm2 = useProps(props => props.alarm_2);
  const alarm3 = useProps(props => props.alarm_3);
  const alarm4 = useProps(props => props.alarm_4);
  const alarm5 = useProps(props => props.alarm_5);
  const alarm6 = useProps(props => props.alarm_6);

  const handleJump = useThrottleFn(
    (code: string) => {
      router.push(`/${code}`);
    },
    { wait: 80 }
  ).run;

  const onClickLeft = React.useCallback(() => {
    router.back();
  }, []);

  const clockList = [alarm1, alarm2, alarm3, alarm4, alarm5, alarm6]
    .map((item, index) => {
      return {
        title: clockNames[`alarm_${index + 1}`] || `闹钟${index + 1}`,
        ...decodeClock(item, `alarm_${index + 1}`),
        code: `alarm_${index + 1}`,
      };
    })
    .filter(item => item.setted !== false);

  const renderTime = (time: number, is24: boolean) => {
    let hours = Math.floor(time / 60);
    let period = hours >= 12 ? Strings.getLang('PM') : Strings.getLang('AM');

    if (!is24) hours = hours % 12 || 12;

    if (is24) period = '';

    const minutes = time % 60;

    return (
      <View className={styles.timeBox}>
        <Text className={styles.hour}>{`${String(hours).padStart(2, '0')}:${String(
          minutes
        ).padStart(2, '0')}`}</Text>
        <Text className={styles.ap}>{period}</Text>
      </View>
    );
  };

  return (
    <View className={styles.view}>
      <NavBar
        title={deviceName}
        className={styles.navBar}
        customClass={styles.borBot}
        slot={{
          left: (
            <View className={styles.tabTopIconWrapLeft} onClick={onClickLeft}>
              {['back'].map(item => (
                <Image src={`/newImage/${item}.png`} key={item} />
              ))}
            </View>
          ),
        }}
      />
      <ScrollView
        scrollY
        refresherTriggered
        className={clsx(styles.slideUpContent)}
        style={{
          height: `calc(100vh - ${HeaderHeight}px - ${sysInfo.statusBarHeight}px)`,
        }}
      >
        <View
          style={{
            marginTop: 20,
          }}
        >
          {clockList.map(item => {
            return (
              <View
                className={styles.card}
                key={item.code}
                onClick={() => {
                  handleJump(`clockEdit?code=${item.code}`);
                }}
              >
                <View className={styles.clockBox}>
                  <View>
                    <Text className={styles.title}>{item.title}</Text>
                    {renderTime(item.startTime, timeMode === '24h')}
                    <View className={styles.subBox}>
                      <Text className={styles.text1}>
                        {`${Strings.getLang('music')}: ${
                          item.musicPower
                            ? Strings.getLang(item.musicSet + item.music.replace('ringtone', ''))
                            : Strings.getLang('mute')
                        }`}
                      </Text>
                      <Text>
                        {Strings.getLang('advanceTime')}: {item.advanceTime}
                        {Strings.getLang('minute')}
                      </Text>
                    </View>
                    <View className={styles.subBox}>
                      <Text className={styles.text1}>{`${Strings.getLang('lightMode')}: ${
                        item.lampPower ? Strings.getLang(item.lightMode) : Strings.getLang('close')
                      }`}</Text>

                      <Text
                        style={{
                          color: '#fff',
                          background: '#074669',
                          padding: '4rpx',
                        }}
                      >
                        {repeatArrtoStr(item.repeat)}
                      </Text>
                    </View>
                  </View>
                  <View>
                    <Switch
                      checked={item.status}
                      size="56rpx"
                      stopClickPropagation
                      onChange={e => {
                        const newData = {
                          ...item,
                          status: e.detail,
                          weeks: item.repeat,
                          ringtone: item.music,
                          volumeSet: item.voice,
                          brightValue: item.light,
                        };

                        const res = encodeClock(newData);
                        console.log('🐫 ~ file:!!!!! ~ res:', res);
                        publishDps({
                          [item.code]: res,
                        });
                      }}
                    />
                  </View>
                </View>
              </View>
            );
          })}
        </View>
      </ScrollView>
    </View>
  );
}

export default Home;
